<?php
	require_once(dirname(__FILE__)."/../../config.php");
	require_once(dirname(__FILE__)."/HostDao.php");
	require_once(dirname(__FILE__)."/../common/crypt/Crypt.php");
?>
<?php
/*
 * Proxy DB
 * Created: 200904 (TT Tsai)
 *
 *
 */

class WFProxyDao extends WFHostDao {
	// my error handling
	private $errMessage = "";

	// Constructor
	public function __construct( $dbconfig, $uid) {
		parent::__construct( $dbconfig["table"]["proxylist"]["name"], $dbconfig, $uid);
	}

	// add
	public function add( $sname, $sinfo) {
		// password encryption
		$enc_str = parent::encrypt($sinfo["password"]);
		if( parent::isFailed() ) {
			$this->errMessage = "[proxyinfo] encryption module failed(encrypt): ".parent::getErrMessage();
			return;
		}
		$sinfo["password"] = $enc_str;
		parent::add( $sname, json_encode($sinfo));
	}
	public function add_str( $sname, $sinfo) {
		// data validation
		$sinfo_json = json_decode( $sinfo, true);
		if( $sinfo_json == null ) {
			$this->errMessage = "[proxyinfo] incorrect format";
			return;
		}
		$this->add( $sname, $sinfo_json);
	}

	// del
	public function del($rid) {
		// data validation
		if( !is_numeric($rid) ) {
			$this->errMessage = "[proxyid] should be a number";
			return;
		}
		parent::del($rid);
	}

	// update
	public function update( $rid, $sname, $sinfo) {
		// data validation
		if( !is_numeric($rid) ) {
			$this->errMessage = "[proxyid] should be a number";
			return;
		}
		// password encryption

		if(isset($sinfo['password'])){
			$enc_str = parent::encrypt($sinfo["password"]);
			if( parent::isFailed() ) {
				$this->errMessage = "[proxyinfo] encryption module failed(encrypt): ".parent::getErrMessage();
				return;
			}
			$sinfo["password"] = $enc_str;
		}else{
			$query_result = parent::getOriginalInfo($rid);
			if($query_result != FALSE && isset($query_result[0]) ) {
				$jsonobj = json_decode( $query_result[0]["hostinfo"], true);
				if($jsonobj!= null){
					$sinfo['password'] = $jsonobj["password"];
				}else{
					$sinfo['password'] = '';
				}
			}
		}
		parent::update( $rid, $sname, json_encode($sinfo));
	}
	public function update_str( $rid, $sname, $sinfo) {
		// conver to json
		$sinfo_json = json_decode( $sinfo, true);
		if( $sinfo_json == null ) {
			$this->errMessage = "[proxyinfo] incorrect format";
			return;
		}
		$this->update( $rid, $sname, $sinfo_json);
	}

	// getall
	public function getall() {
		return parent::getall();
	}

	// getinfo
	public function getinfo($rid) {
		return parent::getinfo($rid);
	}

	// isFailed
	public function isFailed() {
		if( $this->errMessage != "" ) {
			return TRUE;
		}
		return parent::isFailed();
	}

	//
	public function getErrMessage() {
		if( $this->errMessage != "" ) {
			return $this->errMessage;
		}
		return parent::getErrMessage();
	}
}
?>
